<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';

import { computed, markRaw, ref } from 'vue';

import { AuthenticationLogin, ImageCaptcha, z } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { getCaptchaApi } from '#/api/core/index';
import { useAuthStore } from '#/store';

defineOptions({ name: 'Login' });

const authStore = useAuthStore();
const refreshCaptcha = ref(false);
// const uniqueId: string = uuidv4();

const formSchema = computed((): VbenFormSchema[] => {
  return [
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: $t('authentication.usernameTip'),
      },
      fieldName: 'accountName',
      formItemClass: 'col-span-12',
      label: $t('authentication.username'),
      rules: z.string().min(1, { message: $t('authentication.usernameTip') }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: $t('authentication.password'),
      },
      fieldName: 'passWord',
      formItemClass: 'col-span-12',
      label: $t('authentication.password'),
      rules: z.string().min(1, { message: $t('authentication.passwordTip') }),
    },
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '图片验证码',
      },
      fieldName: 'verificationCode',
      label: '图片验证码',
      formItemClass: 'col-span-8',
      rules: z.string().min(1, { message: '请输入图片验证码' }),
    },
    {
      component: markRaw(ImageCaptcha),
      fieldName: 'key',
      componentProps: {
        api: getCaptchaApi,
        refresh: refreshCaptcha,
        'onUpdate:refresh': (e: boolean) => {
          refreshCaptcha.value = e;
        },
      },
      formItemClass: 'col-span-4',
      rules: z.string().refine((value) => value, {
        message: $t('authentication.verifyRequiredTip'),
      }),
    },
  ];
});

const onSubmit = (values: any) => {
  authStore.authLogin(values).catch(() => {
    refreshCaptcha.value = true;
  });
};
</script>

<template>
  <AuthenticationLogin
    :form-schema="formSchema"
    :loading="authStore.loginLoading"
    :show-code-login="true"
    :show-telephone-login="true"
    :show-forget-password="false"
    :show-qrcode-login="true"
    :show-register="false"
    :show-remember-me="false"
    :show-third-party-login="false"
    @submit="onSubmit"
  />
</template>
